-- @preview-file on clear

-- EnemyActionSystem.lua
-- 敌人动作系统，独立于玩家动作系统

local EnemyActionSystem = {}
EnemyActionSystem.__index = EnemyActionSystem

function EnemyActionSystem.new(enemyType, movementSystem)
    local instance = setmetatable({
        enemyType = enemyType, -- "sword", "archer", "broadsword", "boss"
        movementSystem = movementSystem,
        
        spineNode = nil,
        currentAnimation = "idle",
        
        -- 不同类型敌人的Spine路径
        spinePaths = {
            sword = "model/sword/sword",
            archer = "model/archer/archer",
            broadsword = "model/broadsword/broadsword",
            boss = "model/boss/boss"
        },
        
        -- 动画映射
        animationMap = {
            -- 剑士
            sword_idle = "idle",
            sword_walk = "walk",
            sword_attack = "chop",
            sword_dash1 = "dash1",
            sword_dash2 = "dash2",
            sword_dash3 = "dash3",
            sword_hurt = "waiting",
            
            -- 弓箭手
            archer_idle = "idle",
            archer_walk = "walk",
            archer_attack = "shoot",
            archer_hurt = "waiting",
            
            -- 刀兵
            broadsword_idle = "idle",
            broadsword_walk = "walk",
            broadsword_attack_a1 = "a1",
            broadsword_attack_a1walk = "a1walk",
            broadsword_attack_a2 = "a2",
            broadsword_attack_a3 = "a3",
            broadsword_hurt = "waiting",
            
            -- Boss (没有idle，只有walk)
            boss_walk = "walk",
            boss_attack_a1 = "a1",    -- 下劈
            boss_attack_a2 = "a2",    -- 上挑
            boss_dash1 = "dash1",     -- 进入冲锋
            boss_dash2 = "dash2",     -- 持续冲锋跑
            boss_dun = "dun",         -- 半蹲准备起跳
            boss_jump = "jump",       -- 起跳
            boss_fall = "fall",       -- 下劈
            boss_hurt = "waiting"
        },
        
        scale = 0.1,  -- 测试场景中为原来的十分之一
        animationSpeed = 1.0,
        
        _isAttacking = false,
        _currentAttackAnim = nil,
        _attackTimer = 0,
        _attackDuration = 0,
        
        _isDashing = false,  -- 剑士专用
        _dashPhase = 0,      -- 剑士冲锋阶段
        
        _isCharging = false, -- 刀兵专用（举起刀）
        _isSkillCombo = false, -- 刀兵连斩
        
        _isBossJumpAttack = false, -- Boss跳劈状态
        _bossJumpPhase = 0,        -- Boss跳劈阶段
        
        debugMode = true
    }, EnemyActionSystem)
    
    return instance
end

-- 创建Spine节点
function EnemyActionSystem:createSpineNode()
    local Spine = nil
    local success, spineModule = pcall(require, "Spine")
    if not success then
        print("错误：无法加载Spine模块")
        return nil
    end
    
    Spine = spineModule
    
    local spinePath = self.spinePaths[self.enemyType]
    if not spinePath then
        print("错误：未知的敌人类型: " .. self.enemyType)
        return nil
    end
    
    local spineNode = Spine(spinePath)
    
    if spineNode then
        print("✓ 敌人Spine节点创建成功: " .. self.enemyType)
        
        spineNode.scaleX = self.scale
        spineNode.scaleY = self.scale
        spineNode.recovery = 0.05  -- 快速恢复，允许动画打断
        spineNode.speed = self.animationSpeed
        
        return spineNode
    else
        print("✗ 创建敌人Spine节点失败: " .. self.enemyType)
        return nil
    end
end

-- 设置Spine节点
function EnemyActionSystem:setSpineNode(node)
    if not node then 
        print("错误：敌人Spine节点为空")
        return false 
    end
    
    self.spineNode = node
    
    -- 注册动画结束事件监听器
    self.spineNode["AnimationEnd"] = function(animationName, target)
        self:onAnimationEnd(animationName, target)
    end
    
    -- 初始播放空闲动画（Boss除外）
    if self.enemyType ~= "boss" then
        self:playAnimation("idle", true)
    else
        self:playAnimation("walk", true)  -- Boss初始为走路
    end
    
    return true
end

-- 动画结束事件处理
function EnemyActionSystem:onAnimationEnd(animationName, target)
    if self.debugMode then
        print("敌人动画结束: " .. animationName .. " (类型: " .. self.enemyType .. ")")
    end
    
    if self._isAttacking and animationName == self._currentAttackAnim then
        self:_handleAttackAnimationEnd()
    elseif self._isDashing and self.enemyType == "sword" then
        self:_handleDashAnimationEnd()
    elseif self._isBossJumpAttack and self.enemyType == "boss" then
        self:_handleBossJumpAttackEnd()
    end
end

-- 处理攻击动画结束
function EnemyActionSystem:_handleAttackAnimationEnd()
    self._isAttacking = false
    self._currentAttackAnim = nil
    self._attackTimer = 0
    
    if self.enemyType == "broadsword" then
        self._isCharging = false
        if self._isSkillCombo then
            -- 继续连斩
            self._isSkillCombo = false
            self:playAttackAnimation("a3")  -- 技能连斩
            return
        end
    end
    
    -- 返回空闲或行走状态
    self:playAnimation("idle", true)
end

-- 处理剑士冲锋动画结束
function EnemyActionSystem:_handleDashAnimationEnd()
    if self._dashPhase == 1 then
        -- dash1结束，进入dash2
        self._dashPhase = 2
        self:playAnimation("dash2", true)
    elseif self._dashPhase == 2 then
        -- dash2结束，进入dash3
        self._dashPhase = 3
        self:playAnimation("dash3", false)
    elseif self._dashPhase == 3 then
        -- dash3结束，冲锋完成
        self._isDashing = false
        self._dashPhase = 0
        self:playAnimation("idle", true)
    end
end

-- 处理Boss跳劈动画结束
function EnemyActionSystem:_handleBossJumpAttackEnd()
    if self._bossJumpPhase == 1 then
        -- dun结束，进入jump
        self._bossJumpPhase = 2
        self:playAnimation("jump", false)
    elseif self._bossJumpPhase == 2 then
        -- jump结束，进入fall
        self._bossJumpPhase = 3
        self:playAnimation("fall", false)
    elseif self._bossJumpPhase == 3 then
        -- fall结束，跳劈完成
        self._isBossJumpAttack = false
        self._bossJumpPhase = 0
        self:playAnimation("walk", true)
    end
end

-- 播放动画
function EnemyActionSystem:playAnimation(animationType, loop)
    if not self.spineNode then return false end
    
    local animKey = self.enemyType .. "_" .. animationType
    local spineAnim = self.animationMap[animKey]
    
    if not spineAnim then
        -- Boss没有idle，如果请求idle则播放walk
        if self.enemyType == "boss" and animationType == "idle" then
            animKey = "boss_walk"
            spineAnim = self.animationMap[animKey]
        else
            spineAnim = animationType  -- 直接使用动画名称
        end
    end
    
    local loopParam = loop or false
    local success = self.spineNode:play(spineAnim, loopParam)
    
    if success then
        self.currentAnimation = animKey
        if self.debugMode then
            print("敌人播放动画: " .. spineAnim .. " (循环: " .. tostring(loopParam) .. ")")
        end
        return true
    else
        print("敌人播放动画失败: " .. spineAnim)
        return false
    end
end

-- 播放攻击动画
function EnemyActionSystem:playAttackAnimation(attackType)
    if not self.spineNode then return false end
    
    local animKey = self.enemyType .. "_attack"
    if self.enemyType == "broadsword" then
        animKey = animKey .. "_" .. attackType
    end
    local spineAnim = self.animationMap[animKey]
    
    if not spineAnim then
        spineAnim = attackType  -- 直接使用动画名称
    end
    
    -- 设置攻击持续时间
    local attackDurations = {
        ["chop"] = 0.5,
        ["shoot"] = 0.6,
        ["a1"] = 0.4,
        ["a2"] = 0.5,
        ["a3"] = 0.8,
        ["a1"] = 0.6,    -- Boss下劈
        ["a2"] = 0.5,    -- Boss上挑
        ["dash1"] = 0.3,
        ["dash2"] = 0.5,
        ["dash3"] = 0.4,
        ["dun"] = 0.3,
        ["jump"] = 0.4,
        ["fall"] = 0.5
    }
    
    self._attackDuration = attackDurations[spineAnim] or 0.5
    
    local success = self.spineNode:play(spineAnim, false)
    
    if success then
        self._isAttacking = true
        self._currentAttackAnim = spineAnim
        self._attackTimer = 0
        
        if self.debugMode then
            print("敌人播放攻击动画: " .. spineAnim .. " (类型: " .. attackType .. ")")
        end
        return true
    else
        print("敌人播放攻击动画失败: " .. spineAnim)
        return false
    end
end

-- 开始剑士冲锋
function EnemyActionSystem:startDash()
    if self.enemyType ~= "sword" then return false end
    
    self._isDashing = true
    self._dashPhase = 1
    return self:playAnimation("dash1", false)
end

-- 开始Boss跳劈
function EnemyActionSystem:startBossJumpAttack()
    if self.enemyType ~= "boss" then return false end
    
    self._isBossJumpAttack = true
    self._bossJumpPhase = 1
    return self:playAnimation("dun", false)
end

-- 打断当前动画
function EnemyActionSystem:interruptAnimation()
    if self.spineNode then
        self.spineNode.recovery = 0  -- 立即打断
        if self.debugMode then
            print("敌人动画被打断")
        end
    end
end

-- 播放受伤动画
function EnemyActionSystem:playHurtAnimation()
    local animKey = self.enemyType .. "_hurt"
    local spineAnim = self.animationMap[animKey]
    
    if spineAnim then
        self:interruptAnimation()  -- 打断当前动画
        local success = self.spineNode:play(spineAnim, false)
        
        if success then
            -- 设置计时器，受伤动画后恢复
            self._hurtTimer = 0.3
            return true
        end
    end
    return false
end

-- 更新动作系统
function EnemyActionSystem:update(dt)
    if not self.spineNode then return end
    
    -- 更新攻击计时器
    if self._isAttacking then
        self._attackTimer = self._attackTimer + dt
        if self._attackTimer >= self._attackDuration then
            self:_handleAttackAnimationEnd()
        end
    end
    
    -- 更新受伤计时器
    if self._hurtTimer and self._hurtTimer > 0 then
        self._hurtTimer = self._hurtTimer - dt
        if self._hurtTimer <= 0 then
            self._hurtTimer = nil
            -- 受伤动画结束，恢复空闲状态
            if self.enemyType ~= "boss" then
                self:playAnimation("idle", true)
            else
                self:playAnimation("walk", true)
            end
        end
    end
end

-- 获取动画状态
function EnemyActionSystem:getAnimationState()
    return {
        currentAnimation = self.currentAnimation,
        isAttacking = self._isAttacking,
        isDashing = self._isDashing,
        dashPhase = self._dashPhase,
        isCharging = self._isCharging,
        isBossJumpAttack = self._isBossJumpAttack,
        bossJumpPhase = self._bossJumpPhase
    }
end

-- 设置敌人面向方向
function EnemyActionSystem:setFacingDirection(isFacingRight)
    if self.spineNode then
        self.spineNode.fliped = isFacingRight
    end
end

-- 设置缩放
function EnemyActionSystem:setScale(scale)
    self.scale = scale
    if self.spineNode then
        self.spineNode.scaleX = scale
        self.spineNode.scaleY = scale
    end
end

-- 清理资源
function EnemyActionSystem:cleanup()
    if self.spineNode then
        self.spineNode["AnimationEnd"] = nil
        if self.spineNode.parent then
            self.spineNode:removeFromParent()
        end
        self.spineNode = nil
    end
end

return EnemyActionSystem